package com.jxin.mall.core.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.validation.constraints.NotNull;

/**
 * @author 蔡佳新
 * @version 1.0
 * @since jdk 1.8
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {
    /**类名为null的异常信息*/
    private static final String NON_NULL_NAME_REQUIRED = "non null name required";
    /**类字节码为null的异常信息*/
    private static final String NON_NULL_CLAZZ_REQUIRED = "non null clazz required";
    /**
     * pring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    /**
     * 根据实例名和类型获得实例
     * @param  name 实例名
     * @param  clazz 字节码对象
     * @return spring上下文中的对应实例
     * @throws BeansException 找不到实例
     * @author 蔡佳新
     */
    public static <T> T getBean(@NotNull String name, @NotNull Class<T> clazz) throws BeansException {
        Assert.notNull(name, NON_NULL_NAME_REQUIRED);
        Assert.notNull(clazz, NON_NULL_CLAZZ_REQUIRED);
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 根据类型获得实例
     * @param  clazz 字节码对象
     * @return spring上下文中的对应实例
     * @throws BeansException 找不到实例
     * @author 蔡佳新
     */
    public static <T> T getBean(@NotNull Class<T> clazz) throws BeansException {
        Assert.notNull(clazz, NON_NULL_CLAZZ_REQUIRED);
        return applicationContext.getBean(clazz);
    }
}
